<script setup lang="ts">
import {reactive, ref, unref, watch} from 'vue'
import {Form} from '@/components/Form'
import {useI18n} from '@/hooks/web/useI18n'
import {ElButton} from 'element-plus'
import {required} from '@/utils/formRules'
import {useForm} from '@/hooks/web/useForm'
import {loginApi, getInfo, getRouters} from '@/api/login'
import type {UserLoginType} from '@/api/login/types'
import {useCache} from '@/hooks/web/useCache'
import {useAppStore} from '@/store/modules/app'
import {usePermissionStore} from '@/store/modules/permission'
import {useRouter} from 'vue-router'
import type {RouteLocationNormalizedLoaded, RouteRecordRaw} from 'vue-router'

const appStore = useAppStore()

const permissionStore = usePermissionStore()

const {currentRoute, addRoute, push} = useRouter()

const {t} = useI18n()

const {wsCache} = useCache()

const rules = {
  username: [required],
  password: [required]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'logo',
    colProps: {
      span: 24
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: ''
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: ''
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    }
  },
  // {
  //   field: 'other',
  //   component: 'Divider',
  //   label: t('login.otherLogin'),
  //   componentProps: {
  //     contentPosition: 'center'
  //   }
  // },
  {
    field: 'otherIcon',
    colProps: {
      span: 24
    }
  }
])

// const iconSize = 30

// const remember = ref(false)

const {register, elFormRef, methods} = useForm()

const loading = ref(false)

// const iconColor = '#999'

// const redirect = ref<string>('')

// watch(
//   () => currentRoute.value,
//   (route: RouteLocationNormalizedLoaded) => {
//     redirect.value = route?.query?.redirect as string
//   },
//   {
//     immediate: true
//   }
// )

// 登录
const signIn = async () => {
  const formRef = unref(elFormRef)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const {getFormData} = methods
      const formData = await getFormData<UserLoginType>()
      const res: any = await loginApi(formData)
        .catch(() => {
        })
        .finally(() => (loading.value = false))
      //登陆成功
      if (res) {
        wsCache.set('token', res.data.access_token) //存储Token
        getUserInfo()
      }
    }
  })
}

// 获取角色信息/路由
const getUserInfo = async () => {
  //获取用户信息
  const res: any = await getInfo()
    .catch(() => {
    })
    .finally(() => {
    })
  if (res) {
    wsCache.set(appStore.getUserInfo, res.user) //存储用户信息
  }
  await getRouter()
}
const getRouter = async () => {
  const res: any = await getRouters()
    .catch(() => {
    })
    .finally(() => {
    })
  if (res) {
    const routers = res.data || []
    wsCache.set('roleRouters', routers) //存储路由
    await permissionStore.generateRoutes(routers).catch(() => {
    })
    permissionStore.getAddRouters.forEach((route) => {
      // console.log(route, 'route')
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    // push({ path: redirect.value || permissionStore.addRouters[0].path })
    // if (permissionStore?.addRouters[0]?.path == '/:path(.*)*') {
    //   push({
    //     path: '/'
    //   })
    // } else {
    //   push({
    //     path:
    //       permissionStore?.addRouters[0]?.path +
    //       '/' +
    //       permissionStore?.addRouters[0]?.children[0]?.path
    //   })
    // }
    // console.log(permissionStore?.addRouters)
    push({
      path:
        permissionStore?.addRouters[0]?.path +
        '/' +
        permissionStore?.addRouters[0]?.children[0]?.path
    })
  }
}

document.onkeydown = function (e) {
  let key = (window as any).event.keyCode
  //回车事件
  if (key === 13) {
    signIn()
  }
}
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    @register="register"
  >
    <template #logo>
      <!--      <svg aria-hidden="true" class="w-md h-14">-->
      <!--        <use xlink:href="#icon-login_logo_text" />-->
      <!--      </svg>-->
      <img class="w-md h-14" src="@/assets/imgs/login_logo_text.png">
    </template>

    <!-- <template #tool>
      <div class="flex justify-between items-center w-[100%]">
        <ElCheckbox v-model="remember" :label="t('login.remember')" size="small" />
        <ElLink type="primary" :underline="false">{{ t('login.forgetPassword') }}</ElLink>
      </div>
    </template> -->

    <template #login>
      <ElButton :loading="loading" type="primary" class="w-[100%]" @click="signIn">
        {{ t('login.login') }}
      </ElButton>
    </template>
    <!-- 
    <template #otherIcon>
      <div class="flex justify-between w-[100%]">
        <Icon
          icon="ant-design:github-filled"
          :size="iconSize"
          class="cursor-pointer anticon"
          :color="iconColor"
        />
        <Icon
          icon="ant-design:wechat-filled"
          :size="iconSize"
          class="cursor-pointer anticon"
          :color="iconColor"
        />
        <Icon
          icon="ant-design:alipay-circle-filled"
          :size="iconSize"
          :color="iconColor"
          class="cursor-pointer anticon"
        />
        <Icon
          icon="ant-design:weibo-circle-filled"
          :size="iconSize"
          :color="iconColor"
          class="cursor-pointer anticon"
        />
      </div>
    </template> -->
  </Form>
</template>

<style lang="less" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
</style>
